<template>
  <div class="profile">
    <!-- 顶部导航栏 -->
    <div class="navbar">
      <div class="navbar-left">
        <el-button type="primary" link @click="$router.push('/dashboard')">
          <el-icon><ArrowLeft /></el-icon>
          返回仪表盘
        </el-button>
      </div>
      <div class="navbar-center">
        <h1 class="page-title">个人中心</h1>
      </div>
      <div class="navbar-right">
        <el-dropdown @command="handleCommand">
          <el-button circle>
            <el-icon><User /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="logout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="profile-container">
        <!-- 用户头像和基本信息 -->
        <div class="profile-header">
          <div class="avatar-section">
            <AvatarUpload 
              v-model="avatarUrl"
              @success="handleAvatarSuccess"
            />
          </div>
          <div class="user-info">
            <h2 class="username">{{ userStore.userInfo?.username }}</h2>
            <p class="user-role">
              <el-tag :type="userStore.userInfo?.role === 0 ? 'danger' : 'primary'">
                {{ userStore.userInfo?.role === 0 ? '管理员' : '普通用户' }}
              </el-tag>
            </p>
            <p class="user-status">
              <el-tag :type="userStore.userInfo?.status === 1 ? 'success' : 'danger'">
                {{ userStore.userInfo?.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </p>
            <p class="join-time">
              加入时间：{{ formatDate(userStore.userInfo?.createdAt) }}
            </p>
          </div>
        </div>

        <!-- 用户信息表单 -->
        <div class="profile-form">
          <h3 class="form-title">个人信息</h3>
          <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="100px"
            size="large"
          >
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input
                    v-model="profileForm.email"
                    placeholder="请输入邮箱"
                    prefix-icon="Message"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input
                    v-model="profileForm.phone"
                    placeholder="请输入手机号"
                    prefix-icon="Phone"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="profileForm.gender" placeholder="请选择性别">
                    <el-option label="未知" :value="0" />
                    <el-option label="男" :value="1" />
                    <el-option label="女" :value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="生日" prop="birthday">
                  <el-date-picker
                    v-model="profileForm.birthday"
                    type="date"
                    placeholder="请选择生日"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="profileForm.remark"
                type="textarea"
                :rows="4"
                placeholder="请输入备注信息"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                :loading="updateLoading"
                @click="handleUpdateProfile"
              >
                {{ updateLoading ? '保存中...' : '保存修改' }}
              </el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 账户安全 -->
        <div class="security-section">
          <h3 class="form-title">账户安全</h3>
          <div class="security-items">
            <div class="security-item">
              <div class="security-info">
                <h4>修改密码</h4>
                <p>定期修改密码，保护账户安全</p>
              </div>
              <el-button type="primary" @click="showPasswordDialog = true">
                修改密码
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showPasswordDialog"
      title="修改密码"
      width="400px"
      destroy-on-close
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入原密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button
          type="primary"
          :loading="passwordLoading"
          @click="handleChangePassword"
        >
          确认修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  User,
  SwitchButton,
  UserFilled,
  Camera
} from '@element-plus/icons-vue'
import AvatarUpload from '@/components/AvatarUpload.vue'

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const profileFormRef = ref()
const passwordFormRef = ref()

// 加载状态
const updateLoading = ref(false)
const passwordLoading = ref(false)
const showPasswordDialog = ref(false)

// 头像URL
const avatarUrl = computed({
  get: () => userStore.userInfo?.avatar || '',
  set: (value) => {
    // 通过store更新头像
    if (userStore.userInfo) {
      userStore.userInfo.avatar = value
    }
  }
})

// 个人信息表单
const profileForm = reactive({
  email: '',
  phone: '',
  gender: null,
  birthday: '',
  remark: ''
})

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const profileRules = {
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 头像上传成功处理
const handleAvatarSuccess = async (userData) => {
  try {
    // 更新store中的用户信息
    await userStore.getCurrentUser()
    ElMessage.success('头像更新成功！')
  } catch (error) {
    console.error('更新用户信息失败:', error)
  }
}

// 初始化表单数据
const initForm = () => {
  if (userStore.userInfo) {
    profileForm.email = userStore.userInfo.email || ''
    profileForm.phone = userStore.userInfo.phone || ''
    profileForm.gender = userStore.userInfo.gender
    profileForm.birthday = userStore.userInfo.birthday || ''
    profileForm.remark = userStore.userInfo.remark || ''
  }
}

// 重置表单
const resetForm = () => {
  initForm()
}

// 更新个人信息
const handleUpdateProfile = async () => {
  if (!profileFormRef.value) return

  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      updateLoading.value = true
      try {
        const success = await userStore.updateUserInfo(profileForm)
        if (success) {
          ElMessage.success('个人信息更新成功')
        }
      } finally {
        updateLoading.value = false
      }
    }
  })
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true
      try {
        // 这里应该调用修改密码的API
        // const success = await userApi.changePassword(passwordForm)
        ElMessage.success('密码修改成功，请重新登录')
        showPasswordDialog.value = false
        // 重置表单
        passwordForm.oldPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
        // 退出登录
        userStore.logout()
        await router.push('/login')
      } catch (error) {
        ElMessage.error(error.message || '密码修改失败')
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 处理下拉菜单命令
const handleCommand = async (command) => {
  if (command === 'logout') {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      type: 'warning'
    })
    userStore.logout()
    await router.push('/login')
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

onMounted(() => {
  // 初始化表单数据
  initForm()
})
</script>

<style lang="scss" scoped>
.profile {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.navbar {
  background: white;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.navbar-center {
  .page-title {
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
    margin: 0;
  }
}

.main-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.profile-container {
  max-width: 800px;
  margin: 0 auto;
}

.profile-header {
  background: white;
  border-radius: 12px;
  padding: 32px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 32px;

  .avatar-section {
    text-align: center;
  }

  .user-info {
    flex: 1;

    .username {
      font-size: 24px;
      font-weight: 600;
      color: #2c3e50;
      margin-bottom: 8px;
    }

    .user-role, .user-status, .join-time {
      margin-bottom: 8px;
    }

    .join-time {
      color: #606266;
      font-size: 14px;
    }
  }
}

.profile-form, .security-section {
  background: white;
  border-radius: 12px;
  padding: 32px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .form-title {
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 24px;
    padding-bottom: 12px;
    border-bottom: 1px solid #ebeef5;
  }
}

.security-items {
  .security-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 0;
    border-bottom: 1px solid #ebeef5;

    &:last-child {
      border-bottom: none;
    }

    .security-info {
      h4 {
        font-size: 16px;
        color: #2c3e50;
        margin-bottom: 4px;
      }

      p {
        font-size: 14px;
        color: #606266;
        margin: 0;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .navbar {
    padding: 0 16px;
  }

  .main-content {
    padding: 16px;
  }

  .profile-header {
    flex-direction: column;
    text-align: center;
    gap: 20px;

    .user-info {
      text-align: center;
    }
  }

  .profile-form, .security-section {
    padding: 20px;
  }

  .security-item {
    flex-direction: column;
    align-items: flex-start !important;
    gap: 16px;

    .el-button {
      align-self: stretch;
    }
  }
}
</style> 